package com.le.tester.imooc.oldfairy.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * createTime：2023/6/13 16:40
 * description：deadLock and liveLock
 */
public class DiningPhilosophersDeadlock {


    //五个哲学家
    Phi[] phis = new Phi[5];
    volatile int[] forks = new int[5];

    public DiningPhilosophersDeadlock() {
        for (int i = 0; i < 5; i++) {
            phis[i] = new Phi(i + 1);
            forks[i] = 0;
        }
    }


    class Phi extends Philosopher {

        public Phi(int id) {
            super(id);
        }

        @Override
        public synchronized boolean takeLeft(int[] forks) {
            return super.takeLeft(forks);
        }

        @Override
        public synchronized boolean takeRight(int[] forks) {
            return super.takeRight(forks);
        }

        public void run() {
            while (true) {
                try {
                    //1.触发了deadLock,加上了while，性能贼差
                    this.thinking();
                    while (!this.takeLeft(forks)) {
                        Thread.sleep(1);
                    }
                    //使用标记变量来标记尝试次数的最大值
                    //此时有可能出现五个人不停的同时拿起左边的叉子，同时拿起右边的叉子，liveLock
                    int c = 0;
                    while (!this.takeRight(forks)) {
                        c++;
                        if (c > 100) {
                            this.putLeft(forks);
                            continue;
                        }
                        Thread.sleep(1);
                    }
                    this.eating();
                    this.putLeft(forks);
                    this.putRight(forks);
                    this.finished();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public void run() {
        ExecutorService pool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            pool.submit(phis[i]);
        }
    }

    public static void main(String[] args) {

        DiningPhilosophersDeadlock solver = new DiningPhilosophersDeadlock();
        solver.run();
    }


}
